package org.leaves.mailsend.servlets;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.leaves.mailsend.mail.MailThread;

public class MailServlet extends HttpServlet {
	MailThread mt;

	/**
	 * Constructor of the object.
	 */
	public MailServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	@Override
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		int state = Integer.parseInt(request.getParameter("state"));
		switch (state) {
		case 1:
			mt = new MailThread();
			mt.start();
			System.out.print(mt.getState().name());
			break;
		case 2:
			mt.stopthreak();
			System.out.print(mt.getState().name());
			break;
		}
		try {
			OutputStream out = response.getOutputStream();
			ServletOutputStream ow = response.getOutputStream();
			ow.print(mt.getState().toString());
			ow.flush();
			ow.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	@Override
	public void init() throws ServletException {
		// Put your code here
		MailThread mt = new MailThread();
		this.mt = mt;
		{
			mt.toString();
			mt.start();
		}
	}
}
